<template>
  <TabPane
    :name="name"
    :label="label"
  >
    <Table
      class="app-songs-table"
      :columns="columns"
      :data="songs"
    />
  </TabPane>
</template>

<script lang="tsx">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import { MarkRequired } from 'ts-essentials'
import { CreateQueryParams } from '@nestjsx/crud-request'
import { TableColumn } from 'view-design'
import { Song, getSongs } from '@/api/resources'
import { formateDurationOfSong } from '@/utils'
import { VNode } from 'vue'

type RequiredSong = MarkRequired<Partial<Song>, 'id' | 'title' | 'duration' | 'belongsToArtists'>

@Component({
  name: 'SongsTab'
})
export default class extends Vue {
  private readonly name = 'songs';
  private readonly label = '歌曲';
  @Prop() albumId!: number;
  private songs: RequiredSong[] = [];

  get params (): CreateQueryParams {
    return {
      search: {
        'belongsToAlbum.id': this.albumId
      },
      join: [
        { field: 'belongsToAlbum', select: ['id'] },
        { field: 'belongsToArtists', select: ['id', 'name'] }
      ]
    }
  }

  private columns: TableColumn[] = [
    {
      title: '歌名',
      key: 'title',
      align: 'center',
      render: (h, p) => {
        return (
          <router-link to={{ name: 'LibrarySong', params: { songId: (p?.row as RequiredSong)?.id } }}>
            {(p?.row as RequiredSong)?.title}
          </router-link>
        )
      }
    },
    {
      title: '歌手',
      key: 'artist',
      align: 'center',
      render: (h, p) => {
        const doms: VNode[] = [];
        (p?.row as RequiredSong).belongsToArtists.forEach((artist) => {
          const v = (
            <router-link to={{ name: 'LibraryArtist', params: { artistId: artist.id } }}>
              {artist.name}
            </router-link>
          )
          doms.push(v)
        })
        return <div>{doms}</div>
      }
    },
    {
      title: '时长',
      key: 'duration',
      align: 'center',
      render: (h, p) => {
        return <span>{formateDurationOfSong((p?.row as RequiredSong)?.duration)}</span>
      }
    }
  ];

  @Watch('albumId')
  private async handleAlbumIdUpdated (id: number) {
    if (id > 0) { this.songs = (await getSongs(this.params)).data as Song[] }
  }
}
</script>

<style lang="less" scoped>
@import "../../../../styles/theme";
.app-songs-table {
  &/deep/.ivu-table {
    * {
      background-color: @dark-bg-color;
    }
  }
  &/deep/a {
    &:hover {
      color: @text-color;
    }
    &::after {
      content: ' / ';
    }
    &:last-of-type {
      &::after {
        content: none;
      }
    }
  }
}
</style>
